package com.ruoyi.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VersionUtil {

    private static final Logger log = LoggerFactory.getLogger(ApiCallUtil.class);


    /**
     * 获取版本
     *
     * @param userAgent
     * @return
     */
    public static String getVersion(String userAgent) {

        try {

            Pattern pattern = Pattern.compile("/(\\d+\\.\\d+\\.\\d+)(-SNAPSHOT)?/\\d+$");
            Matcher matcher = pattern.matcher(userAgent);
            if (matcher.find()) {
                return matcher.group(1);
            }

        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        return "";

    }

    /**
     * 大于或者等于
     *
     * @param ver1
     * @param ver2
     * @return
     */
    public static boolean aboveOrEqual(String ver1, String ver2) {

        if (StringUtils.isEmpty(ver1) || StringUtils.isEmpty(ver2)) {
            return false;
        }
        if (StringUtils.equalsIgnoreCase(ver1, ver2)) {
            return true;
        }

        int[] iVer1 = parase(ver1);
        int[] iVer2 = parase(ver2);
        for (int i = 0; i < 3; i++) {
            if (iVer1[i] < iVer2[i]) {
                return false;
            } else if (iVer1[i] > iVer2[i]) {
                return true;
            }
        }

        return true;
    }

    public static boolean above(String ver1, String ver2) {

        if (StringUtils.isEmpty(ver1) || StringUtils.isEmpty(ver2)) {
            return false;
        }
        if (StringUtils.equalsIgnoreCase(ver1, ver2)) {
            return false;
        }

        int[] iVer1 = parase(ver1);
        int[] iVer2 = parase(ver2);
        for (int i = 0; i < 3; i++) {
            if (iVer1[i] < iVer2[i]) {
                return false;
            } else if (iVer1[i] > iVer2[i]) {
                return true;
            }
        }
        return false;
    }

    public static boolean equal(String ver1, String ver2) {

        if (StringUtils.isEmpty(ver1) || StringUtils.isEmpty(ver2)) {
            return false;
        }

        int[] iVer1 = parase(ver1);
        int[] iVer2 = parase(ver2);
        for (int i = 0; i < 3; i++) {
            if (iVer1[i] != iVer2[i]) {
                return false;
            }
        }
        return true;
    }

    public static int[] parase(String ver) {
        int[] v = new int[]{0, 0, 0};
        String[] datas = ver.split("\\.");
        if (datas.length == 3) {
            for (int i = 0; i < 3; i++) {
                v[i] = Integer.parseInt(datas[i]);
            }
        }
        return v;
    }

}
